/* pages/personal/personaldata/personaldata.js */
var configUrl = require('../../../config/config'); //引入配置接口文件
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    payeeInfo: {},
    newPayeeInfo: {},
    //前端展示用的电话字段
    phoneNumberShow: '',
    liablePersonName: '',
    smsCode: '',
    sendTip: '获取验证码',
    //为true时发送按钮不可用
    sendFlag: false,
    sendWait: 60,
    isShowGetUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    //存放页面入参
    options: {}
  },
  bindGetUserInfo: function (e) { //登录-注册
    app.getUserInfo(this.onLoad, this.data.options)
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
  onCloseShowGetUserInfo() { //关闭弹出层
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('绑定入参', options)
    //将页面入参存下来
    this.setData({
      options: options
    })
    if (!wx.getStorageSync('addrCode').provinceCode) {
      app.getUserLocation() //初始化获取定位地址
    }
    if (!wx.getStorageSync('loginMsg')) {
      app.initLogin() //初始化登录
    }
    var loginStateTimer=setInterval(()=>{
      if(wx.getStorageSync('loginMsg').token){
        clearInterval(loginStateTimer)
        if (!this.checkLogin()) {
          return
        }
        if (options) {
          //发送请求获取当前操作经销商的收款人绑定情况
          app.reqFun.requestJson('POST',configUrl.dealerPayeeInfo,options,(res)=>{
            console.log('经销商收款人信息', res)
            if(res.data.success === 1) {
              let payeeInfo = res.data.data
              payeeInfo.dealerCode = options.dealerCode
              payeeInfo.dealerName = options.dealerName
              //最新经销商责任人电话
              if (payeeInfo && payeeInfo.phoneNumber) {
                  let phoneNumberShow = payeeInfo.phoneNumber.substring(0, 3) + '****' + payeeInfo.phoneNumber.substring(7);
                  let liablePersonName = payeeInfo.liablePersonName.replace(/.(?=.)/g, '*')
                  this.setData({
                      phoneNumberShow: phoneNumberShow,
                      liablePersonName: liablePersonName
                  })
              } else {
                wx.showToast({
                  title: '未查询到经销商责任人电话',
                  icon:'none',
                  duration:3000
                })
                return
              }
              //设置原来的收款人信息
              this.setData({
                payeeInfo: payeeInfo
              })
              //设置新的收款人信息
              let newPayeeInfo = this.data.newPayeeInfo
              newPayeeInfo.dealerCode = options.dealerCode
              newPayeeInfo.dealerName = options.dealerName
              let loginMsg = wx.getStorageSync('loginMsg')
              if (loginMsg && loginMsg.userInfo) {
                newPayeeInfo.payeeOpenId = loginMsg.userInfo.openid
                newPayeeInfo.nickname = loginMsg.userInfo.nickname
                newPayeeInfo.icon = loginMsg.userInfo.icon
              }
              this.setData({
                newPayeeInfo: newPayeeInfo
              })
            } else {
              wx.showToast({
                title: '经销商信息查询失败，' + res.data.msg,
                icon:'none',
                duration:3000
              })
            }
          })
        }
      }
    },100)
  },
  backeIndex() {
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
  /**
   * 设置收款人真实姓名
   */
  setPayeeName:function(e){
    let that = this;
    let newPayeeInfo = that.data.newPayeeInfo
    newPayeeInfo.payeeName = e.detail.value
    that.setData({
      newPayeeInfo: newPayeeInfo
    })
  },
    /**
   * 设置收款人真实姓名
   */
  setSmsCode:function(e){
    let that = this;
    let smsCode = e.detail.value
    that.setData({
      smsCode: smsCode
    })
  },
  /**
   * 检查登录状态，弹出登录窗
   */
  checkLogin() {
    let that =this
    if (!wx.getStorageSync('loginMsg').loginState) {
      if (wx.getUserProfile) {
        app.getUserProfile(function(){
          that.setData({
            getPhoneNumberData:{
              isShowGetPhoneNumber:true
            }
          })
        })
      } else {
        if(!wx.getStorageSync('loginMsg').bindingPhone){
          that.setData({
            getPhoneNumberData:{
              isShowGetPhoneNumber:true
            }
          })
        }
      }
      // this.setData({
      //   isShowGetUserInfo: true
      // })
      //未登录
      console.log('未登录')
      return false
    }
    //已登录
    console.log('未登录')
    return true
  },
  /**
   * 发送短信验证码
   */
  sendSmsCode() {
    //检查登录
    if (!this.checkLogin()) {
      return
    }
    //先校验责任人电话
    if (!this.data.payeeInfo.phoneNumber) {
      wx.showToast({
        title: '预留手机号不能为空',
        icon:'none',
        duration:3000
      })
      return
    }
    //再校验收款人真实姓名
    if (!this.data.newPayeeInfo.payeeName) {
      wx.showToast({
        title: '收款人真实姓名不能为空',
        icon:'none',
        duration:3000
      })
      return
    }
    //发送控制防止多次获取验证码
    if (this.data.sendFlag) {
      return
    }
    this.setData({
      sendFlag: true
    });
    //可再次获取验证码倒计时
    let sendTime = setInterval(function() {
      this.setData({
        sendFlag: true,
        sendTip: this.data.sendWait + 's后可重发',
        sendWait: this.data.sendWait - 1
      });
      if (this.data.sendWait < 0) {
        clearInterval(sendTime)
        this.setData({
          sendTip: '获取验证码',
          sendWait: 60,
          sendFlag: false
        });
      }
    }.bind(this), 1000);
    //发送请求到后台
    let sendParam = {
      "phoneNumber": this.data.payeeInfo.phoneNumber,
      "payeeName": this.data.newPayeeInfo.payeeName
    }
    app.reqFun.requestJson('POST',configUrl.bindDealerPayeeSendSms,sendParam,(res)=>{
      if(res.data.success === 1) {
        wx.showToast({
          title: '发送成功',
          duration:2000
        })
      } else {
        wx.showToast({
          title: '获取短信验证码失败，' + res.data.msg,
          icon:'none',
          duration:3000
        })
      }
    })
  },
  /**
   * 确认绑定收款人
   */
  checkBind() {
    //检查登录
    if ((!this.checkLogin())) {
      return
    }
    //再校验收款人真实姓名
    if (!this.data.newPayeeInfo.payeeName) {
      wx.showToast({
        title: '收款人真实姓名不能为空',
        icon:'none',
        duration:3000
      })
      return
    }
    //短信验证码不为空
    if (!this.data.smsCode) {
      wx.showToast({
        title: '验证码不能为空',
        icon:'none',
        duration:3000
      })
      return
    }
    //先校验短信验证码正确性
    let validateParam = {
      "phoneNumber": this.data.payeeInfo.phoneNumber,
      "smsCode": this.data.smsCode
    }
    app.reqFun.requestForm('POST',configUrl.validateBindDealerPayee,validateParam,(res)=>{
      if(res.data.success === 1) {
        //验证码正确进入绑定确认
        this.confirmBind()
      } else {
        wx.showToast({
          title: res.data.msg,
          icon:'none',
          duration:3000
        })
      }
    })
  },
  /**
   * 确认绑定
   */
  confirmBind() {
    let that = this
    let content = '【' + that.data.payeeInfo.dealerCode + that.data.payeeInfo.dealerName + '】'
    if (that.data.payeeInfo.payeeName) {
      content += '已绑定收款人【' + that.data.payeeInfo.payeeName + '】，'
      content += '是否确认更换为【' + that.data.newPayeeInfo.payeeName + '】'
    } else {
      content += '将绑定收款人【' + that.data.newPayeeInfo.payeeName + '】'
    }
    //绑定确认弹窗
    wx.showModal({
      title: '绑定提示',
      content: content,
      success: function (res) {
        if (res.confirm) {
          //发送绑定请求
          let bindParam = that.data.newPayeeInfo
          app.reqFun.requestJson('POST',configUrl.bindDealerPayee,bindParam,(res)=>{
            if(res.data.success === 1) {
              wx.navigateTo({
                url: '/packagMy/pages/returnApp/returnApp',
              })
            } else {
              wx.showToast({
                title: '绑定失败，' + res.data.msg,
                icon:'none',
                duration:3000
              })
            }
          })
        } else {
          wx.showToast({
            title: '已取消操作',
            icon:'none',
            duration:3000
          })
        }
      }
    })
  }
})
